<?php

namespace App\Http\Controllers;
use App\Jobs\AppointList;
use App\Models\Appoint;
use App\Models\ScanRecord;
use App\Models\UserLogin;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class SignController extends Controller
{
    public function syncScanRecord(Request $request)
    {
        //return new JsonResponse(['code'=>200,'msg'=>'成功'],200);

        try {
            if(!$request->input('openid') && !$request->input('unionid') && !$request->input('xopenid')){
                return new JsonResponse(['code'=>500,'msg'=>'参数错误'],500);
            }

            $user_id = 0;
            //查询用户是否已经注册
            if($request->input('unionid') || $request->input('xopenid')) {
                $userLoginQuery = UserLogin::query();
                if ($request->input('unionid')) {
                    $userLoginQuery->where('unionid', $request->input('unionid'));
                } elseif ($request->input('xopenid')) {
                    $userLoginQuery->where('xopenid', $request->input('xopenid'));
                }
                $userLogin = $userLoginQuery->first();
                $user_id = $userLogin?$userLogin->user_id:0;
            }
            //如果用户未注册查询用户是否有过扫码记录
            if ($request->input('openid') && !$user_id){
                $scanRecord_ord = ScanRecord::query()->where('openid', $request->input('openid'))->first();
                $user_id = $scanRecord_ord?$scanRecord_ord->user_id:0;
            }
            $scanRecord = new ScanRecord();
            $scanRecord->openid = $request->input('openid')??'';
            $scanRecord->unionid = $request->input('unionid')??'';
            $scanRecord->xopenid = $request->input('xopenid')??'';
            $scanRecord->user_id = $user_id;
            $scanRecord->hospital_id = $request->input('hospital_id')??0;
            $scanRecord->save();
            return new JsonResponse(['code'=>200,'msg'=>'成功'],200);

        } catch (\Exception $exception) {
            return new JsonResponse(['code'=>500,'msg'=>$exception->getMessage()],500);

        }


    }
}
